/*
 * periph.h
 *
 *  Created on: Dec 3, 2012
 *      Author: r.leonov
 */

#include "stm32f10x.h"
#include "stm32f10x_exti.h"
#include "stm32f10x_usart.h"
#include "string.h"

#ifndef PERIPH_H_
#define PERIPH_H_

// Buffer to share COM port settings
extern uint8_t UartSettingsContanier[7];


// ============================ DEVICE CONFIG =================================
typedef struct {
    uint32_t Baudrate;
    uint8_t StopBits;
    uint8_t Parity;
    uint8_t WordLength;
} UART_SETTINGS;

enum dConfig_t {
    dtDefault       = 0b00,
    dtCOM_Port      = 0b01,
    dtSPI_Line      = 0b10,
    dtI2C_Line      = 0b11,
};

extern class Device_t {
private:
    void ParseParametres(uint8_t* PBuf);
public:
    bool IsConfigured;
    dConfig_t Type;
    void Config(dConfig_t ADeviceConfig);
} Device;

// ============================= USART PERIPH =================================
// **defines
#define USART_PERIPH_BUF_SIZE       128
#define USART_PERIPH_DMA_CNL        DMA1_Channel7

class Buf_t {
private:
public:
    uint8_t Buf[USART_PERIPH_BUF_SIZE]; // Buffers
    uint8_t *PBuf;          // pointer to Buffers
    uint32_t WIndx, RIndx;
    uint32_t *PWIndx, *PRIndx;
    bool WasRead(void)    { return (*PRIndx == *PWIndx); }
    uint8_t Read(void)    { uint8_t A = PBuf[(*PRIndx)++]; if ((*PRIndx) > (USART_PERIPH_BUF_SIZE-1)) *PRIndx=0; return A; }
    void Write(uint8_t A) { PBuf[(*PWIndx)++] = A; if ((*PWIndx) > (USART_PERIPH_BUF_SIZE-1)) *PWIndx=0; }
    void Clear(void)      { memset(PBuf, 0, USART_PERIPH_BUF_SIZE); *PWIndx = 0; }
};

extern Buf_t BufToHost, BufToPeriph, BufToSend;

extern class Usart_t {
private:
    uint32_t INeedToTransmit;
    uint8_t *PBuf;
public:
    void Send(uint8_t AByte)        { USART_SendData(USART2, AByte); while(USART_GetFlagStatus(USART2, USART_FLAG_TC) == RESET); }
    void Init();
    void Task(void);
//    friend class Buf_t;
} UsartPeriph;

extern "C" {
void USART2_IRQHandler(void);
}
#endif /* PERIPH_H_ */
